package com.xln.interceptor;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xln.pojo.Admin;
import com.xln.service.AdminService;
import com.xln.util.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;
import java.util.Map;

import static sun.management.Agent.error;

@Component
@Slf4j
public class AdminTokenInterceptor implements HandlerInterceptor {

    public static ThreadLocal<Admin> threadLocal = new ThreadLocal<>();

    @Resource
    private AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("用户token：{}",token);

        if (token == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                log.info("用户未登录");
                request.getRequestDispatcher("/login").forward(request,response);
                return false;
            }
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("Authorization")) {
                    token = cookie.getValue();
                    log.info("用户cookie：{}",token);
                    break;
                }
            }
        }
        String Admin;
        try {
            Map userMap = Token.parseToken(token);
            Admin = (String)userMap.get("username");
            log.info("用户名：{}",Admin);

        } catch (Exception e) {
            log.error("token解析失败");
            request.getRequestDispatcher("/login").forward(request,response);
            throw new RuntimeException(e);
        }
        Admin abAdmin = adminService.getOne(Wrappers.<Admin>query().eq("username", Admin));
        if (abAdmin == null){
            log.info("账号不存在");
            request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
        threadLocal.set(abAdmin);


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        threadLocal.remove();
    }
}
